<?php

require_once 'Pipes/Exception.php';
require_once 'PipesImpl/Config.php';
require_once 'PipesImpl/Storage.php';

class Pipes_Storage implements PipesImpl_Storage
{
	private $_pdo = null;
	
	public function __construct(PipesImpl_Config $config) {
		$this->_pdo = $config->pdo;
	}
	
	public function getRecord(PipesImpl_Statement $statement) {
		$pdoStmt = $this->_pdo->prepare($statement->value);
		if ($pdoStmt === false || $pdoStmt->execute($statement->substitutions) === false) {
			throw new Pipes_Exception('Problem preparing statement [' . $statement->value . ']');
		}
		
		$return = $pdoStmt->fetch(PDO::FETCH_ASSOC);
		$pdoStmt->closeCursor();
		return $return;
	}
	
	public function getRecords($name) {
		$name = strtolower($name);
		$sql = "SELECT * FROM {$name}s";
		$statement = $this->_pdo->query($sql);
		if ($statement === false) {
			throw new Pipes_Exception('Problem executing query [' . $sql . ']');
		}
		
		$return = $statement->fetchAll(PDO::FETCH_ASSOC);
		$statement->closeCursor();
		return $return;
	}
	
	public function add($name, array $properties) {
		$columns = array_keys($properties);
		$valueHolders =  array();
		foreach ($columns as $column) {
			$valueHolders[] = ":{$column}";
		}
		
		$columnsSql = implode('`, `', $columns);
		$valueHoldersSql = implode(', ', $valueHolders);
		$sql = "INSERT INTO {$name}s (`{$columnsSql}`) VALUES ({$valueHoldersSql})";
		
		$statement = $this->_pdo->prepare($sql);
		$statement->execute($properties);
	}
	
	public function modify($name, array $properties) {
		$idColumn = "{$name}_id";
		
		$updates = array();
		foreach ($properties as $key => $value) {
			if ($key == $idColumn) {
				continue;
			}
			$updates[] = "`{$key}` = :{$key}";
		}
		
		$updatesSql = implode(', ', $updates);
		$sql = "UPDATE {$name}s SET {$updatesSql} WHERE `{$idColumn}` = :{$idColumn}";
		
		$statement = $this->_pdo->prepare($sql);
		$statement->execute($properties);
	}

	public function remove($name, $id) {
		$idColumn = "{$name}_id";
		$sql = "DELETE FROM {$name}s WHERE `{$idColumn}` = ?";
		
		$statement = $this->_pdo->prepare($sql);
		$statement->execute(array($id));
	}
}

